package com.rxt.thermopro.ui.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.app.common.base.BaseFragment
import com.rxt.thermopro.R
import com.rxt.thermopro.adapter.ProfileListAdapter
import com.rxt.thermopro.app.LocalDataDao
import com.rxt.thermopro.bean.ProfileBean
import com.rxt.thermopro.ui.dialog.ProfileBottomDialog
import com.rxt.thermopro.ui.dialog.TypeBottomDialog
import com.rxt.thermopro.ui.dialog.TypeBottomDialog.Companion.TYPE_TARGET_TEMP
import com.rxt.thermopro.ui.fragment.EditProfileFragment.Companion.TYPE_EDIT_TARGET
import com.rxt.thermopro.viewmodel.BleMessageViewModel.Companion.DEVICE_TYPE_TP960
import com.rxt.thermopro.viewmodel.DeviceStatusViewModel
import com.rxt.thermopro.viewmodel.EventViewModel
import com.rxt.thermopro.viewmodel.ProfileViewModel
import kotlinx.android.synthetic.main.fragment_set_profile.*

class SetProfileFragment : BaseFragment<ProfileViewModel>() {
    override fun layoutId(): Int {
        return R.layout.fragment_set_profile
    }

    companion object {
        private const val ARG_DEVICE_POSITION = "devicePosition"
        private const val ARG_PROFILE_NAME = "profileName"
        private const val ARG_PROFILE_DEVICE_TYPE = "deviceType"
        private const val ARG_ADDRESS = "address"

        fun newInstance(devicePosition: Int, profileName: String): SetProfileFragment {
            return SetProfileFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_DEVICE_POSITION, devicePosition)
                    putString(ARG_PROFILE_NAME, profileName)
                }
            }
        }

        fun newInstance(
            devicePosition: Int,
            profileName: String,
            deviceType: Int,address:String
        ): SetProfileFragment {
            return SetProfileFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_DEVICE_POSITION, devicePosition)
                    putString(ARG_PROFILE_NAME, profileName)
                    putInt(ARG_PROFILE_DEVICE_TYPE, deviceType)
                    putString(ARG_ADDRESS, address)
                }
            }
        }
    }

    private lateinit var adapter: ProfileListAdapter
    private val profileList = mutableListOf<ProfileBean>()
    private val mHandler = Handler(Looper.getMainLooper())

    private lateinit var mDeviceStatusViewModel: DeviceStatusViewModel
    private lateinit var mEventViewModel: EventViewModel
    private var mPosition = 1
    private var mProfileName = ""
    private var isSignalTemp = false
    private var headerProfile: ProfileBean? = null
    private var mDeviceType = 1
    private var mAddress = ""

    override fun initView(savedInstanceState: Bundle?) {
        mPosition = arguments?.getInt(ARG_DEVICE_POSITION) ?: 1
        mProfileName = arguments?.getString(ARG_PROFILE_NAME) ?: ""
        mAddress = arguments?.getString(ARG_ADDRESS) ?: ""
        mDeviceType = arguments?.getInt(ARG_PROFILE_DEVICE_TYPE) ?: 1
        isSignalTemp = mDeviceType == DEVICE_TYPE_TP960

        if (isSignalTemp) {
            linear1.isVisible = false
        }

        mDeviceStatusViewModel =
            ViewModelProvider(requireActivity()).get(DeviceStatusViewModel::class.java)
        mEventViewModel = ViewModelProvider(requireActivity()).get(EventViewModel::class.java)
        adapter = ProfileListAdapter(profileList)
        adapter.setProfilePresenter(ProfilePresenter())
        recyclerProfile.layoutManager = LinearLayoutManager(context)
        recyclerProfile.adapter = adapter

        mViewModel.profileListData.observe(this, Observer {
            if (adapter.list.isNotEmpty()) {
                adapter.clear()
            }
            adapter.addAll(it)
        })

        mViewModel.profileHeardData.observe(this, Observer {
            if (it.checked) {
                viewCheck.isChecked = true
            }
            headerProfile = it
        })
        mEventViewModel.refreshProfile.observeInFragment(this, Observer {
            if (headerProfile?.checked == true) {
                mViewModel.initProfileData("", isSignalTemp)
            } else {
                mViewModel.initProfileData(
                    adapter.list.first { item -> item.checked }.name,
                    isSignalTemp
                )
            }
            if (LocalDataDao.INSTANCE.hasNeedSetProbeProfile(mAddress,mPosition)) {
                mDeviceStatusViewModel.refreshProfile(mAddress,mDeviceType,mPosition)
            }
        })

        setListener()
        mViewModel.initProfileData(mProfileName, isSignalTemp)
    }

    private fun setListener() {
        backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        viewCheck.setOnCheckedChangeListener { _, isChecked ->
            headerProfile?.checked = isChecked
            if (isChecked) {
                mHandler.post {
                    adapter.clearChecked()
                }
            }
        }

        viewEdit.setOnClickListener {
            val list = adapter.list.filter { it.checked }
            val currentData = if (list.isNotEmpty()) {
                list[0]
            } else {
                val bean = LocalDataDao.INSTANCE.getProfileHeader()
                bean.checked = headerProfile?.checked ?: false
                headerProfile = bean
                headerProfile
            }
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    EditProfileFragment.newInstance(TYPE_EDIT_TARGET, currentData!!)
                )
                .addToBackStack("main")
                .commit()
        }

        linear1.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(
                    R.anim.translate_into, R.anim.translate_out,
                    R.anim.translate_into_pop, R.anim.translate_out_exit
                )
                .add(
                    R.id.mainContent,
                    AmbientTempFragment.newInstance()
                )
                .addToBackStack("main")
                .commit()
        }

        viewDiscard.setOnClickListener {
//            LocalDataDao.INSTANCE.resetProfile()
            val bean = ProfileBean("MEAT", "", mutableListOf(), singleTemp = false)
            mDeviceStatusViewModel.setProFile(mPosition, bean,mAddress)
            requireActivity().onBackPressed()
        }

        viewSave.setOnClickListener {
            val list = adapter.list.filter { it.checked }
            if (list.isNotEmpty()) {
                mDeviceStatusViewModel.setProFile(mPosition, list.first(),mAddress)
                requireActivity().onBackPressed()
            } else {
                val bean = LocalDataDao.INSTANCE.getProfileHeader()
                bean.checked = headerProfile?.checked ?: false
                headerProfile = bean
                headerProfile?.let {
                    if (it.checked) {
                        mDeviceStatusViewModel.setProFile(mPosition, it,mAddress)
                        requireActivity().onBackPressed()
                    }
                }
            }
        }
    }

    inner class ProfilePresenter() {

        fun onItemSelectClick(view: View, position: Int) {
            if (adapter.list[position].itemValues.isNotEmpty()) {
//                val listDialog = BottomDialog()
//                listDialog.showDialog(childFragmentManager)
//                listDialog.updateData(adapter.get(position).itemValues, position)
//                listDialog.setOnDialogBluetoothListener(object :
//                    BottomDialog.OnDialogProfileListener {
//                    override fun onItemClick(currentIndex: Int, itemPosition: Int) {
//                        println("123->  currentIndex=$currentIndex   itemPosition=$itemPosition  ")
//                        val currentItem = adapter.list[position]
//                        currentItem.profileValue =
//                            currentItem.itemValues[itemPosition].itemName + " " +
//                                    currentItem.itemValues[itemPosition].itemValue
//                        currentItem.highTemperatureNum =
//                            currentItem.itemValues[itemPosition].itemValue
//                        currentItem.checked = true
//                        currentItem.itemValues[itemPosition].checked = true
//                        adapter.update(currentItem, position, itemPosition)
//                    }
//                })
                val dialog = ProfileBottomDialog()
                dialog.setProfileData(adapter.get(position).itemValues, position)
                dialog.showDialog(childFragmentManager)
                dialog.setOnItemSelectListener(object : ProfileBottomDialog.OnItemSelectListener {
                    override fun onSelected(index: Int, profileIndex: Int) {
                        println("123->  currentIndex=$index   itemPosition=$profileIndex  ")
                        val currentItem = adapter.list[profileIndex]
                        currentItem.profileValue =
                            currentItem.itemValues[index].itemName + " " +
                                    currentItem.itemValues[index].itemValue
                        currentItem.highTemperatureNum =
                            currentItem.itemValues[index].itemValue
                        currentItem.checked = true
                        currentItem.itemValues[index].checked = true
                        adapter.update(currentItem, position, index)
                    }
                })
                viewCheck.isChecked = false
            }
        }

        fun onItemClick(view: View, position: Int) {
//            if (adapter.list[position].itemValues.isNotEmpty()) {
//                val listDialog = BottomDialog()
//                listDialog.showDialog(childFragmentManager)
//                listDialog.updateData(adapter.get(position).itemValues, position)
//                listDialog.setOnDialogBluetoothListener(object :
//                    BottomDialog.OnDialogProfileListener {
//                    override fun onItemClick(currentIndex: Int, itemPosition: Int) {
//                        println("123->  currentIndex=$currentIndex   itemPosition=$itemPosition  ")
//                        val currentItem = adapter.list[position]
//                        currentItem.profileValue =
//                            currentItem.itemValues[itemPosition].itemName + " " +
//                                    currentItem.itemValues[itemPosition].itemValue
//                        currentItem.highTemperatureNum =
//                            currentItem.itemValues[itemPosition].itemValue
//                        currentItem.checked = true
//                        currentItem.itemValues[itemPosition].checked = true
//                        adapter.update(currentItem, position, itemPosition)
//                    }
//                })
//            } else {
//                mHandler.post {
//                    println("123-> onItemClick  no childItem=$position")
//                    adapter.checkPosition(position)
//                }
//            }
            mHandler.post {
                println("123-> onItemClick  no childItem=$position")
                adapter.checkPosition(position)
            }
            viewCheck.isChecked = false
        }

        fun onItemChecked(view: View, position: Int) {
            mHandler.post {
                println("123-> onItemChecked=$position")
                adapter.clearCheckPosition(position)
            }
            viewCheck.isChecked = false
        }

        fun onItemClickAdd(itemView: View, position: Int) {
            if (isSignalTemp) {
                parentFragmentManager.beginTransaction()
                    .setCustomAnimations(
                        R.anim.translate_into, R.anim.translate_out,
                        R.anim.translate_into_pop, R.anim.translate_out_exit
                    )
                    .add(
                        R.id.mainContent,
                        CreateProfileFragment.newInstance(TYPE_TARGET_TEMP)
                    )
                    .addToBackStack("main")
                    .commit()
            } else {
                val dialog = TypeBottomDialog()
                dialog.showDialog(childFragmentManager)
                dialog.setOnTypeSelectListener(object : TypeBottomDialog.OnTypeSelectListener {
                    override fun onSelected(type: Int) {
                        parentFragmentManager.beginTransaction()
                            .setCustomAnimations(
                                R.anim.translate_into, R.anim.translate_out,
                                R.anim.translate_into_pop, R.anim.translate_out_exit
                            )
                            .add(
                                R.id.mainContent,
                                CreateProfileFragment.newInstance(type)
                            )
                            .addToBackStack("main")
                            .commit()
                    }
                })
            }
        }
    }
}